package com.ruoyi.web.controller.shop.base;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ApproveMission;
import com.ruoyi.common.core.domain.entity.RestaurantGoods;
import com.ruoyi.common.core.domain.entity.RestaurantGoodsDetail;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.resp.RestaurantGoodsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/1
 **/
@RestController
@RequestMapping("/shop/base/base")
public class ShopBaseController extends BaseController {
    @Resource
    private RestaurantGoodsService restaurantGoodsService;

    @Resource
    private RestaurantGoodsDetailService restaurantGoodsDetailService;

    @Resource
    private BuffetDetailService buffetDetailService;

    @Resource
    private NormalService normalService;

    @Resource
    private ReplaceService replaceService;

    @Autowired
    private ApproveService approveService;

    @Log(title = "菜品导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RestaurantGoods restaurantGoods)
    {
        List<RestaurantGoods> list = restaurantGoodsService.selectRestaurantGoodsList(restaurantGoods);
        List<RestaurantGoodsDTO> restaurantGoodsDTOS = fillToDTO(list);
        ExcelUtil<RestaurantGoodsDTO> util = new ExcelUtil<RestaurantGoodsDTO>(RestaurantGoodsDTO.class);
        util.exportExcel(response, restaurantGoodsDTOS, "菜品");
    }

    @GetMapping("/list")
    public TableDataInfo list(RestaurantGoods restaurantGoods)
    {
        startPage();
        List<RestaurantGoods> list = restaurantGoodsService.selectRestaurantGoodsList(restaurantGoods);
        return getDataTable(fillToDTO(list));
    }

    @GetMapping("/listAll")
    public TableDataInfo listAll(RestaurantGoods restaurantGoods)
    {
        List<RestaurantGoods> list = restaurantGoodsService.selectRestaurantGoodsList(restaurantGoods);
        List<RestaurantGoodsDTO> restaurantGoodsDTOS = fillToDTO(list);
        if (CollectionUtils.isEmpty(restaurantGoodsDTOS)) {
            return getDataTable(restaurantGoodsDTOS);
        }
        return getDataTable(restaurantGoodsDTOS.stream()
                .filter(Objects::nonNull)
//                .filter(r -> "通过".equals(r.getApproveStatus()))
                .filter(r -> "启用".equals(r.getStatus()))
                .collect(Collectors.toList()));
    }

    //("@ss.hasPermi('store:resource:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(fillOneToDTO(restaurantGoodsService.selectRestaurantGoodsById(id)));
    }

    //("@ss.hasPermi('store:resource:add')")
    @Log(title = "菜品管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody RestaurantGoods restaurantGoods)
    {
        restaurantGoods.setStatus("启用");
        restaurantGoods.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = restaurantGoodsService.createRestaurantGoods(restaurantGoods);
        if (result) {
            return success();
        }
        return error();
    }

    //("@ss.hasPermi('store:resource:edit')")
    @Log(title = "菜品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody RestaurantGoods restaurantGoods) {
        restaurantGoods.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = restaurantGoodsService.updateRestaurantGoods(restaurantGoods);
        if (result) {
            return success();
        }
        return error();
    }

    //("@ss.hasPermi('store:resource:remove')")
    @Log(title = "菜品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(restaurantGoodsService.deleteRestaurantGoodsById(id));
    }

    private List<RestaurantGoodsDTO> fillToDTO(List<RestaurantGoods> restaurantGoodsList) {
        if (CollectionUtils.isEmpty(restaurantGoodsList)) {
            return Collections.emptyList();
        }
        List<RestaurantGoodsDTO> restaurantGoodsDTOS = restaurantGoodsList.stream().map(g -> {
            RestaurantGoodsDTO restaurantGoodsDTO = new RestaurantGoodsDTO();
            restaurantGoodsDTO.setId(g.getId());
            restaurantGoodsDTO.setHot(g.getHot());
            restaurantGoodsDTO.setHun(g.getHun());
            restaurantGoodsDTO.setImage(g.getImage());
            restaurantGoodsDTO.setName(g.getName());
            restaurantGoodsDTO.setLocation(g.getLocation());
            restaurantGoodsDTO.setPrice(g.getPrice());
            restaurantGoodsDTO.setTaste(g.getTaste());
            restaurantGoodsDTO.setStatus(g.getStatus());
            restaurantGoodsDTO.setCreateBy(g.getCreateBy());
            restaurantGoodsDTO.setCreateTime(g.getCreateTime());
            restaurantGoodsDTO.setUpdateTime(g.getUpdateTime());
            restaurantGoodsDTO.setUpdateBy(g.getUpdateBy());
//            try {
//                ApproveMission approveMission = approveService.getApproveMissionByActivityd(g.getId(), "菜品信息详情审批");
//                if (approveMission == null) {
//                    restaurantGoodsDTO.setApproveStatus("未提交审批");
//                } else if ("通过".equals(approveMission.getStatus()) || "拒绝".equals(approveMission.getStatus())){
//                    List<RestaurantGoodsDetail> restaurantGoodsDetails = restaurantGoodsDetailService.selectList(RestaurantGoodsDetail.builder().goodsId(g.getId()).build());
//                    Boolean editAfterApprove = false;
//                    if (!CollectionUtils.isEmpty(restaurantGoodsDetails)) {
//                        for (RestaurantGoodsDetail restaurantGoods : restaurantGoodsDetails) {
//                            if (restaurantGoods.getCreateTime().compareTo(approveMission.getApproveTime()) > 0
//                                    || (restaurantGoods.getUpdateTime() != null && restaurantGoods.getUpdateTime().compareTo(approveMission.getApproveTime()) > 0)) {
//                                editAfterApprove = true;
//                                break;
//                            }
//                        }
//                    }
//                    if (editAfterApprove) {
//                        restaurantGoodsDTO.setApproveStatus("修改后未提交审批");
//                    } else {
//                        restaurantGoodsDTO.setApproveStatus(approveMission.getStatus());
//                        restaurantGoodsDTO.setApproveMissionId(approveMission.getId());
//                    }
//                } else {
//                    restaurantGoodsDTO.setApproveStatus(approveMission.getStatus());
//                    restaurantGoodsDTO.setApproveMissionId(approveMission.getId());
//                }
//            } catch (Exception e) {
//                logger.error("菜品信息 获取审批状态失败", e);
//            }
            return restaurantGoodsDTO;
        }).collect(Collectors.toList());
        PageInfo<RestaurantGoods> oldPage = new PageInfo<>(restaurantGoodsList);
        Page<RestaurantGoodsDTO> newPage = new Page<>();
        newPage.addAll(restaurantGoodsDTOS);
        newPage.setTotal(oldPage.getTotal());
        return newPage;
    }
    private RestaurantGoodsDTO fillOneToDTO(RestaurantGoods restaurantGoods) {
        if (restaurantGoods == null) {
            return null;
        }
        RestaurantGoodsDTO restaurantGoodsDTO = new RestaurantGoodsDTO();
        restaurantGoodsDTO.setId(restaurantGoods.getId());
        restaurantGoodsDTO.setHot(restaurantGoods.getHot());
        restaurantGoodsDTO.setHun(restaurantGoods.getHun());
        restaurantGoodsDTO.setImage(restaurantGoods.getImage());
        restaurantGoodsDTO.setName(restaurantGoods.getName());
        restaurantGoodsDTO.setLocation(restaurantGoods.getLocation());
        restaurantGoodsDTO.setPrice(restaurantGoods.getPrice());
        restaurantGoodsDTO.setTaste(restaurantGoods.getTaste());
        restaurantGoodsDTO.setCreateBy(restaurantGoods.getCreateBy());
        restaurantGoodsDTO.setCreateTime(restaurantGoods.getCreateTime());
        restaurantGoodsDTO.setUpdateTime(restaurantGoods.getUpdateTime());
        restaurantGoodsDTO.setUpdateBy(restaurantGoods.getUpdateBy());
//        ApproveMission approveMission = approveService.getApproveMissionByActivityd(restaurantGoods.getId(), "垃圾记录详情审批");
//        restaurantGoodsDTO.setApproveStatus(Optional.ofNullable(approveMission).map(ApproveMission::getStatus).orElse("未提交审批"));
        return restaurantGoodsDTO;
    }
}
